using System;
using System.Windows;
using DesktopWidgetApp.UI.ViewModels;

namespace DesktopWidgetApp.UI.Views
{
    /// <summary>
    /// TaskEditWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TaskEditWindow : Window
    {
        public TaskItemViewModel TaskItem { get; private set; }
        public bool IsConfirmed { get; private set; } = false;

        // 构造函数 - 创建新任务
        public TaskEditWindow()
        {
            InitializeComponent();
            TaskItem = new TaskItemViewModel
            {
                Id = Guid.NewGuid().ToString(),
                Title = string.Empty,
                Description = string.Empty,
                Status = TaskStatus.Todo,
                Priority = Priority.Medium,
                DueDate = DateTime.Now.AddDays(1),
                Tags = string.Empty
            };
            DataContext = TaskItem;
            InitializeUI();
        }

        // 构造函数 - 编辑现有任务
        public TaskEditWindow(TaskItemViewModel existingTask)
        {
            InitializeComponent();
            TaskItem = existingTask.Clone(); // 创建副本以避免直接修改原始任务
            DataContext = TaskItem;
            InitializeUI();
        }

        private void InitializeUI()
        {
            // 初始化状态下拉框
            StatusComboBox.ItemsSource = Enum.GetValues(typeof(TaskStatus));
            StatusComboBox.SelectedItem = TaskItem.Status;

            // 初始化优先级下拉框
            PriorityComboBox.ItemsSource = Enum.GetValues(typeof(Priority));
            PriorityComboBox.SelectedItem = TaskItem.Priority;

            // 初始化截止日期选择器
            DueDatePicker.SelectedDate = TaskItem.DueDate;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            // 验证输入
            if (string.IsNullOrWhiteSpace(TaskItem.Title))
            {
                MessageBox.Show("任务标题不能为空", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 收集UI数据到TaskItem
            TaskItem.Status = (TaskStatus)StatusComboBox.SelectedItem;
            TaskItem.Priority = (Priority)PriorityComboBox.SelectedItem;
            TaskItem.DueDate = DueDatePicker.SelectedDate ?? DateTime.Now.AddDays(1);
            TaskItem.Tags = TagsTextBox.Text.Trim();

            IsConfirmed = true;
            Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            IsConfirmed = false;
            Close();
        }

        private void Window_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}